package org.example.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.entity.ResponseModel;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应头，JSON
        response.setContentType("application/json;charset=utf-8");

        //创建输出流对象
        PrintWriter writer = response.getWriter();

        // 构建输出数据
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        ResponseModel<String> rm = ResponseModel.authSuccess(userDetails.getUsername());

        //响应前端数据
        String jsonString = JSON.toJSONString(rm);
        writer.write(jsonString);

    }
}
